<?php

namespace app\common\library;

use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeAppPayRequest;
use app\common\controller\Api;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\Requirement;
use app\common\model\requirement\Lists;
use app\common\model\User;
use app\common\model\user\LevelLog;
use think\Db;
use think\Env;
use think\Log;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use wechatPay\Wxpay;


/**
 * 统一支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $config;

    public function __construct()
    {
        $this->config = [
            // 小程序appid
            'nmp_app_id' => 'wx8207417d142f8f17',
            // 商户号
            'mch_id' => '1648836793',
            // 商户证书
            'private_key' =>    ROOT_PATH  . str_replace('/', DS, substr('/application/certs/apiclient_key.pem', 1)),
            'certificate' =>    ROOT_PATH  . str_replace('/', DS, substr('/application/certs/apiclient_cert.pem', 1)),
            //证书序列号
            'serial_no' => '1C1BDA35BAA2BB112355D3B16D75AC70931C514A',
            // v3 API 秘钥
            'secret_key' => 'BrIw2rB9j3PY3EL6d1qhuyJLWddLDk59',
            // v2 API 秘钥
            'v2_secret_key' => '26db3e15cfedb44abfbb5fe94fxxxxx',
            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                // 请使用绝对路径
                // '/path/to/wechatpay/cert.pem',
            ],
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
    }
    /**
     * 封装统一支付方法
     *
     */
    public static function pay($id, $type, $userInfo, $pay_type)
    {
        switch ($type) {
            case 'order':
                $order = Order::get($id);
                $money = $order['pay_money'];
                break;
            case 'vip':
                $order = LevelLog::get($id);
                $money = $order['pay_fee'];
                break;
            case 'plaza':
                $order = Lists::get($id);
                $money = $order['pay_money'];
                break;
        }

        if ($money <= 0) {
            $time = time();
            $order->state = 1;
            $order->pay_status = 1;
            $order->opentime = $time;
            $order->status = 1;
            $order->paytime = $time;
        } else {
            if ($pay_type == '0') {
                $sdk = Pay::wxpay($order, $type);
                //微信支付
            } elseif ($pay_type == '1') {
                //微信小程序支付
                $sdk = (new Pay)->minipay($order->sn, $money, $userInfo->openid, $type);
            } elseif ($pay_type == '2') {
                //余额支付
                $sdk =  Pay::yue($order, '');
            } elseif ($pay_type == '3') {
                //支付宝支付
                $sdk = Pay::alipay($order);
            }
        }
        //更换支付方式
        $order->pay_type = $pay_type;
        $order->allowField(true)->save();
        return $sdk ?? '';
    }


    /**
     * 余额支付
     *
     */
    private static function yue($data, $payPwd)
    {
        $user = User::get($data['user_id']);

        if ($user->pay_pwd != md5(md5($payPwd) . 'pcy')) {
            exception('支付密码不正确');
        }

        $totalMoney = bcadd($user->money, $user->no_money, 2);
        if ($data['pay_money'] > $totalMoney) {
            exception('余额不足');
        }
        Db::startTrans();
        try {
            if ($user->no_money > $data['pay_money']) {
                MoneyLog::income($user->id, $data['pay_money'], 1, 503, $data['sn']);
            } else {
                if ($user->no_money > 0) {
                    $money = bcsub($data['pay_money'], $user->no_money, 2);
                    MoneyLog::income($user->id, $user->no_money, 1, 503, $data['sn']);
                } else {
                    $money = $data['pay_money'];
                }
                if ($money > 0) {
                    MoneyLog::income($user->id, $money, 1, 504, $data['sn']);
                }
            }

            self::orderFulfillment($data['sn']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }
    /**
     * 支付宝支付
     *
     */
    private static function alipay($data)
    {
        if (Env::get('app.debug') == true) {
            $data['pay_money'] = 0.01;
        }
        $aop = new AopClient();
        $object['out_trade_no'] = $data['sn'];
        $object['total_amount'] = $data['pay_money'];
        $object['subject'] = '订单支付';
        $json = json_encode($object);
        $request = new AlipayTradeAppPayRequest();
        $request->setNotifyUrl(cdnurl('/api/notify/alipayNotify', true));
        $request->setBizContent($json);
        $result = $aop->sdkExecute($request);
        return $result;
    }
    //小程序下单
    private  function mnpPay($sn, $money, $openid, $attach = 'order')
    {
        // php -f D:\phpstudy_pro\WWW\1246\vendor\wechatpay\wechatpay\bin\CertificateDownloader.php -k BrIw2rB9j3PY3EL6d1qhuyJLWddLDk59 -m 1648836793 -f D:\phpstudy_pro\WWW\1246\application\certs\apiclient_key.pem -s 1C1BDA35BAA2BB112355D3B16D75AC70931C514A -o D:\phpstudy_pro\WWW\1246\application\certs
        // composer exec CertificateDownloader.php -- -k BrIw2rB9j3PY3EL6d1qhuyJLWddLDk59 -m 1648836793 -f /www/wwwroot/1246.ciyuantiaoyue.com/application/certs/apiclient_key.pem -s 1C1BDA35BAA2BB112355D3B16D75AC70931C514A -o /www/wwwroot/1246.ciyuantiaoyue.com/application/certs
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyInstance = Rsa::from("file://" . ROOT_PATH  . str_replace('/', DS, substr('/application/certs/apiclient_key.pem', 1)), Rsa::KEY_TYPE_PRIVATE);

        // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
        $platformPublicKeyInstance = Rsa::from("file://" . ROOT_PATH  . str_replace('/', DS, substr('/application/certs/wechatpay.pem', 1)), Rsa::KEY_TYPE_PUBLIC);
        $merchantCertificateSerial = config('site.serial_no');
        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo("file://" . ROOT_PATH  . str_replace('/', DS, substr('/application/certs/wechatpay.pem', 1)));
        // 构造一个 APIv3 客户端实例
      
        $instance = Builder::factory([
            'mchid'      => config('site.mch_id'),
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        try {
            // 发送请求
            $resp = $instance->chain('v3/pay/transactions/jsapi')->post(
                [
                    'json' => [
                        'appid' =>  config('site.appid'),
                        'mchid'      => config('site.mch_id'),
                        'out_trade_no'  => $sn,
                        'attach'  => $attach,
                        'description'  => '商品购买',
                        'notify_url'  => cdnurl('/api/notify/wechatNotify', true),
                        'amount'         => [
                            'total'    => $money * 100,
                            'currency' => 'CNY',
                        ],
                        'scene_info' => [
                            'payer_client_ip' => $_SERVER["REMOTE_ADDR"],
                        ],
                        'payer' => [
                            'openid' => $openid,
                        ]
                    ],
                ]
            );
            dump(json_decode($resp->getBody(),1));
            return $resp->getBody();
        } catch (\Exception $e) {
            dd($e);
            // 进行错误处理
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {

                $r = $e->getResponse();
            dd($r->getBody());

                echo $r->getBody();
            }
        }
    }
    //小程序下单
    public static function minipay($sn, $pay_fee, $openid, $attach = 'order')
    {
        $out_trade_no = $sn;
        $money = $pay_fee;
        if (Env::get('app.debug') == true) {
            $money = 0.01;
        }
        if (empty($out_trade_no)) {
            exception('缺少参数order_sn');
        }
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = Wxpay::getNonceStr();
        $appid = config('site.appid'); //appID
        $mchid = config('site.mch_id'); //商户ID
        $xlid =  config('site.serial_no'); //证书序列号
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['attach'] = $attach;
        $data['description'] = '商品描述'; //商品描述
        $data['out_trade_no'] = $out_trade_no; //订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] =  cdnurl('/api/notify/wechatNotify', true); //需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $money * 100; //金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];; //场景ip
        $data['payer']['openid'] = $openid; //openid
        $array = json_encode($data, JSON_UNESCAPED_UNICODE);
        Log::write($data);

        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = Wxpay::getSign($array, $urlarr['path'], $noncestr, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $key);
        //头部信息
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        // try {
        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        // $client = new \GuzzleHttp\Client(['base_uri' => $url]);
        // $response = $client->request('POST', '/v3/pay/transactions/jsapi', [
        //     'json' => $data,
        //     'headers' => [
        //         'Accept'=>'application/json',
        //         'Content-Type'=>'application/json',
        //         'User-Agent'=>'*/*',
        //         'Authorization'=>'WECHATPAY2-SHA256-RSA2048 ' . $token
        //     ]
        // ]);
        // } catch (\Exception $e) {
        //     // 进行错误处理
        //     if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
        //         $r = $e->getResponse();
        //         echo $r->getBody();
        //     }
        // }


        $res = Wxpay::curl_post_https($url, $array, $header);

        $prepay_id = json_decode($res, true)['prepay_id'];
        $paySign = Wxpay::getWechartSign($appid, $time, $noncestr, 'prepay_id=' . $prepay_id);
        $payData = [
            'timeStamp' => (string) $time,
            'nonceStr' => $noncestr,
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'RSA',
            'paySign' => $paySign
        ];
        return $payData;
    }
    // /var/spool/cron
    // 0 1 * * *  /usr/bin/php /www/wwwroot/1214test.ciyuantiaoyue.com/1214-3.0/public/index.php /addons/crontab/autotask/index
    //微信app支付
    private static function wxpay($order,  $attach)
    {
        $out_trade_no = $order['sn'];
        $money = $order['pay_money'];
        if (Env::get('app.debug') == true) {
            $money = 0.01;
        }
        if (empty($out_trade_no)) {
            exception('缺少参数order_sn');
        }
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = Wxpay::getNonceStr();
        $appid = config('site.app_id'); //appID
        $mchid = config('site.mch_id'); //商户ID
        $xlid =  config('site.serial_no'); //证书序列号
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['attach'] = $attach;
        $data['description'] = '商品描述'; //商品描述
        $data['out_trade_no'] = $out_trade_no; //订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] =  cdnurl('/api/notify/wechatNotify', true); //需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $money * 100; //金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];; //场景ip
        // $data['payer']['openid'] = $openid; //app支付不需要openid
        $data = json_encode($data);

        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = Wxpay::getSign($data, $urlarr['path'], $noncestr, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $key);
        //头部信息
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        $res = Wxpay::curl_post_https($url, $data, $header);
        $prepay_id = json_decode($res, true)['prepay_id'];


        $paySign = Wxpay::getWechartSign($appid, $time, $noncestr, $prepay_id);
        $payData = [
            'appid' => $appid,
            'partnerid' => $mchid,
            'prepayid' => $prepay_id,
            'package' => "Sign=WXPay",
            'noncestr' => $noncestr,
            'timestamp' => (string) $time,
            'sign' => $paySign
        ];
        return $payData;
    }
    //会员开通成功
    public static function vipFulfillment($id, $trade_no = null)
    {
        $log = LevelLog::get($id);
        if (!$log) {
            exception('订单不存在');
        }
    }
    //订单支付成功
    public static function orderFulfillment($sn, $trade_no = null)
    {

        try {
            $order = Order::get([
                'status' => 0,
                'sn' => $sn,
            ]);

            if (!$order) {
                exception('订单不存在');
            }

            // $user = User::get($order->user_id);
            // dd($order->distribution == '2');


            // if ($order->distribution == '2') {
            //     $data['status'] = 2;

            //     $data['qh_image'] = build($order->id);
            // }

            $order->transaction_id = $trade_no;
            $order->paytime = time();
            $order->status = '10';
            $order->save();
            // $user->setInc('consumption', $order->pay_money);

        } catch (\Exception $e) {
            exception($e);
        }
    }
}
